<template>
  <div>
    <div class="app-container">
      <el-row style="margin-bottom: 10px;">
        <el-button-group>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="toAdd">{{$t('table.add')}}</el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" @click="toUpdate">{{$t('table.update')}}</el-button>
          <el-button type="primary" size="small" icon="el-icon-delete" @click="toDelete">{{$t('table.delete')}}</el-button>
          <el-button type="primary" size="small" icon="el-icon-document" @click="toDetail">{{$t('table.detail')}}</el-button>
        </el-button-group>
      </el-row>
      <tree-table :data="data" :columns="columns" :expandAll="true" border highlight-current-row @row-click="onRowClick">
        <el-table-column :label="$t('org.address')" property="fullAddress"></el-table-column>
      </tree-table>
    </div>
    <transition name="fade">
      <router-view/>
    </transition>
  </div>
</template>

<script>
  import Vue from 'vue'
  import VueRouter from 'vue-router'
  import treeTable from '@/components/TreeTable'
  import { fetchQuery, fetchDelete, fetchSave, fetchUpdate } from '@/api/restful'

  export default {
    components: { treeTable },
    data() {
      return {
        data: [],
        columns:[{
          text: 'org.name',
          value: 'name'
        }],
        selectedRow: null,
        baseUrl: '/org'
      };
    },
    methods: {
      onRowClick(row, event, column) {
        this.selectedRow = row;
      },
      toAdd(){
        this.$router.push({path: '/add'});
      },
      toUpdate(){
        if(this.selectedRow)
          this.$router.push({path: '/update'});
        else{
          this.$message({
            message: this.$t('notify.unselectedRow'),
            type: 'warning'
          });
        }
      },
      toDelete(){
        if(this.selectedRow) {
          this.$confirm(
            this.$t('notify.confirmToDel'),
            this.$t('notify.title.prompt'),
            {
              confirmButtonText: this.$t('dialog.confirm'),
              cancelButtonText: this.$t('dialog.cancel'),
              type: 'warning'
            }
          ).then(() => {
            this.loading = true;
            fetchDelete(this.baseUrl + '/' + this.selectedRow.id).then(response => {
              if (response.data.success) {
                this.$notify.success({
                  title: this.$t('notify.title.success'),
                  message: response.data.msg
                });
                this.load();
              }
              else {
                this.loading = false;
                this.$notify.warning({
                  title: this.$t('notify.title.fail'),
                  message: response.data.msg
                });
              }
            })
          }).catch(() => {
            this.loading = false;
            this.$message({
              type: 'info',
              message: this.$t('notify.cancelDel')
            });
          });
        }
        else{
          this.$message({
            message: this.$t('notify.unselectedRowToDel'),
            type: 'warning'
          });
        }
      },
      toDetail(){
        if(this.selectedRow)
          this.$router.push({path: '/detail'});
        else{
          this.$message({
            message: this.$t('notify.unselectedRow'),
            type: 'warning'
          });
        }
      },
      load(){
        fetchQuery('/org/queryByUser', {authCode: 'ORG'}).then(response => {
          if(response.data.success){
            this.selectedRow = null;
            var rows = response.data.result;
            var roots = getRoots(rows);
            if(this.data.length>0){
              this.data.splice(0, this.data.length);
            }
            for(let i=0; i<roots.length; i++){
              roots[i].children = getChildren(rows, roots[i].id);
              Vue.set(this.data, i, roots[i]);
            }
          }
        });
        function getRoots(rows){
          var roots = [];
          for(let i=0; i< rows.length; i++){
            let row = rows[i];
            if(row.parent==null || row.parent.id==0){
              roots.push(row);
            }
            else{
              let isChild = false;
              for(let j = 0; j<rows.length; j++){
                if(row.parent.id==rows[j].id){
                  isChild = true;
                  break;
                }
              }
              if(!isChild){
                roots.push(row);
              }
            }
          }
          return roots;
        }
        function getChildren(rows, pid){
          var children = [];
          for(let i=0; i< rows.length; i++){
            let row = rows[i];
            if(row.parent!=null && row.parent.id==pid){
              children.push(row);
              row.children = getChildren(rows, row.id);
            }
          }
          return children;
        }
      }
    },
    mounted(){
      this.load();
    },
    router: new VueRouter({
      mode: 'abstract',
      routes: [
        { path: '/add', component: () => import('./dialog/add') },
        { path: '/update', component: () => import('./dialog/update') },
        { path: '/detail', component: () => import('./dialog/detail') }
      ]
  })
  };
</script>
